var express = require('express');
var router = express.Router();
const orderController = require("../controllers/order_controller")
const mongoUtil = require("../models/mongo_util")
// 获取用户订单
// var page=1
// var pagesize=10
router.post("/getorder", (req, res) => {
    var {
        userid,
        page, //页码
        pagesize //每页数量
    } = req.body
    if (page && pagesize) {
        orderController.getuserorder({userid,page,pagesize}, (result) => {
            res.json(result)
        })
    } else {
        orderController.getuserorder(userid, (result) => {
            res.json(result)
        })
    }

})

// 添加订单
// 测试数据
// var orderList = {
//     "orderId": 9803,
//     "orderNo": "16357619150253971",
//     "totalPrice": 5009,
//     "payType": 1,
//     "orderStatus": 1,
//     "orderStatusString": "已支付",
//     "createTime": "2021-11-01 18:18:35",
//     "usergoodsorderlist": [{
//             "goodsId": 10902,
//             "goodsCount": 1,
//             "goodsName": "华为 HUAWEI P40 冰霜银 全网通5G手机",
//             "goodsCoverImg": "https://newbee-mall.oss-cn-beijing.aliyuncs.com/images/p40-silver.png",
//             "sellingPrice": 4299
//         },
//         {
//             "goodsId": 10233,
//             "goodsCount": 2,
//             "goodsName": "纪梵希高定香榭天鹅绒唇膏306#",
//             "goodsCoverImg": "/goods-img/04949c0e-87df-445b-96dd-29e7fc69f734.jpg",
//             "sellingPrice": 355
//         }
//     ]
// }
router.post("/order", (req, res) => {
    // orderList为对象，包含订单的信息和购买的商品
    var {
        userid,
        orderList
    } = req.body
    if (Object.prototype.toString.call(orderList) == '[object Object]' && orderList != {}) {
        orderController.userAddorder(userid, (result) => {
            if (result.code == 200 && result.data.length > 0) {
                var whereStr = {
                    'userId': userid,
                    // 'goodsId':goodsId
                }
                result.data.forEach(item => {
                    if (item.orderlist.length > 0) {
                        item.orderlist.unshift(orderList)
                        console.log("+++++++", item.orderlist);
                        var updateStr1 = {
                            $set: {
                                'orderlist': item.orderlist
                            }
                        };
                        mongoUtil.getCollection("order").then(collection => {
                            console.log(whereStr, "+++++++", updateStr1);
                            collection.updateOne(whereStr, updateStr1, function (err, res) {
                                console.log("添加成功");
                            });
                        })
                        res.json({
                            code: 200,
                            err: null,
                            data: [{
                                orderNo: orderList.orderNo
                            }],
                            msg: "添加订单数据成功"
                        })
                    } else {
                        item.orderlist.push(orderList)
                        var updateStr2 = {
                            $set: {
                                'orderlist': item.orderlist
                            }
                        };
                        mongoUtil.getCollection("order").then(collection => {

                            collection.updateOne(whereStr, updateStr2, function (err, res) {
                                console.log("添加成功");
                            });
                        })
                        res.json({
                            code: 200,
                            err: null,
                            data: [{
                                orderNo: orderList.orderNo
                            }],
                            msg: "添加订单数据成功"
                        })
                    }
                })
            } else {
                mongoUtil.getCollection('order').then(collection => {
                    collection.insertOne({
                        userId: userid,
                        orderlist: [orderList]
                    }, function (err, res) {});
                })
                res.json({
                    code: 200,
                    err: null,
                    data: [{
                        orderNo: orderList.orderNo
                    }],
                    msg: "添加订单数据成功"
                })
            }
            // res.json(result)
        })
    } else {
        res.json({
            code: 401,
            data: [],
            msg: "数据必须为对象，且不为空"
        })
        // res.json(result)
    }
})
// 查看订单详情
router.get("/orderdetail/:orderNo", (req, res) => {
    var {
        orderNo
    } = req.params
    orderController.getorderdetail(orderNo, (result) => {
        res.json(result)
    })
})
// 取消订单
// 测试数据
// var orderNo = ['16357619150253971']
router.delete("/order", (req, res) => {
    var {
        userid,
        orderNo
    } = req.body
    if (orderNo.length > 0) {
        orderController.userdeleteorder(userid, (result) => {
            if (result.code == 200 && result.data.length > 0) {
                var whereStr = {
                    'userId': userid,
                    // 'goodsId':goodsId
                }
                result.data.forEach(item => {
                    var orderlist = item.orderlist.filter(ite => {
                        return !orderNo.includes(ite.orderNo)
                    })
                    var updateStr = {
                        $set: {
                            'orderlist': orderlist
                        }
                    };
                    mongoUtil.getCollection("order").then(collection => {

                        collection.updateOne(whereStr, updateStr, function (err, res) {
                            console.log("取消订单成功");
                        });
                    })
                })
                res.json({
                    code: 200,
                    data: [],
                    mag: "取消订单成功"
                })
            } else {
                res.json({
                    code: 401,
                    data: [],
                    mag: "没找到订单数据"
                })
            }
            // res.json(result)
        })
    } else {
        res.json({
            code: 401,
            data: [],
            msg: "取消订单失败"
        })
    }
})
//提交订单
// 测试数据
// var payType = 2
router.post("/payorder", (req, res) => {
    var {
        orderNo,
        payType
    } = req.body
    orderController.payuserOrder(orderNo, (result) => {
        if (result.code == 200) {
            result.data.forEach(item => {
                item.orderlist.forEach(ite => {
                    ite["payType"] = payType
                })
                var whereStr = {
                    'orderlist.orderNo': orderNo
                    // 'goodsId':goodsId
                }

                var updateStr = {
                    $set: {
                        'orderlist': item.orderlist
                    }
                };
                mongoUtil.getCollection("order").then(collection => {

                    collection.updateOne(whereStr, updateStr, function (err, res) {
                        console.log("提交订单成功");
                    });
                })

                res.json({
                    code: 200,
                    data: [],
                    mag: "提交订单成功"
                })
            })
        } else {
            res.json({
                code: 401,
                data: [],
                mag: "提交订单失败"
            })
        }
    })
})


//搜索订单
router.get("/searchOrder/:orderNo", (req, res) => {
    var {
        orderNo
    } = req.params
    orderController.searchuserOrder(orderNo, (result) => {

        res.json(result)
    })
})
//后台修改订单
// putorderList对象
var putorderList = {
    Distribution: "",
    Exwarehouse: "出库",
}
// orderNo数组
// var orderNo = ['16357619150253972', '16357619150253973']
router.put("/putOrder", (req, res) => {
    var {
        orderNo
    } = req.body
    for (var key in putorderList) {
        if (putorderList[key].length > 0) {
            var putlist = {
                orderNo,
                status: putorderList[key]
            }
            orderController.putuserOrder(putlist, (result) => {
                res.json(result)
            })
        }
    }


})
module.exports = router